package com.ray.friendslist;

import com.ray.friendslist.api.VkLoginRequest;
import com.ray.friendslist.token.VkTokenManager;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.webkit.WebView;
import android.webkit.WebViewClient;

@SuppressLint("SetJavaScriptEnabled")
public class VkLoginActivity extends Activity {

	private WebView mWebview;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		mWebview = (WebView) findViewById(R.id.webVeiw);
		mWebview.getSettings().setJavaScriptEnabled(true);
		mWebview.loadUrl(new VkLoginRequest().getLoginRequest());
		mWebview.setWebViewClient(new WebViewClient() {
			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				super.onPageStarted(view, url, favicon);
				if (Uri.parse(url).getEncodedFragment() != null
						&& Uri.parse(url).getEncodedFragment().substring(0, 12)
								.equals("access_token"))
					VkLoginActivity.this.setVisible(false);
			}

			@Override
			public void onPageFinished(WebView view, String url) {
				super.onPageFinished(view, url);
				if (Uri.parse(url).getEncodedFragment() != null
						&& Uri.parse(url).getEncodedFragment().substring(0, 12)
								.equals("access_token")) {
					VkTokenManager.setTooken(url);
					Log.i("ray", "token is --- "
							+ VkTokenManager.getTooken());
					Intent intent = new Intent(VkLoginActivity.this,
							VkFriendsListActivity.class);
					VkLoginRequest.setAuthorised(true);
					startActivity(intent);
					finish();
					Log.i("ray", "Activity is opened");
				}
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	/*
	 * public boolean onKeyDown(int keyCode, KeyEvent event) { if ((keyCode ==
	 * KeyEvent.KEYCODE_BACK) && mWebview.canGoBack()) { mWebview.goBack();
	 * return true; } return super.onKeyDown(keyCode, event); }
	 */
}
